<%--
  Created by IntelliJ IDEA.
  User: HUYUZHU
  Date: 2020/9/4
  Time: 15:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <c:import url="../template/_header.jsp"/>
    <title>${resource.title}-知了[团队知识管理应用]</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>

<body>
<div class="re-main">
    <c:import url="../template/_navbar.jsp"/>
    <div class="re-box-6 mt-85">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="re-box re-box-decorated resource-post">
                        <div class="resource-post-box">
                            <%-------------------- 资源标题 --------------------%>
                            <h1 class="h3 resource-post-title">${resource.title}</h1>
                            <%-------------------- 资源标签 --------------------%>
                            <c:if test="${!resource.labelName.equals(\"该资源无标签\")}">
                                <ul class="resource-post-info">
                                    <li class="font-text-darkgray">标签:&nbsp;</li>
                                    <c:forEach var="label" items="${resource.labelName.split(',|，')}" varStatus="s">
                                        <c:forEach var="labelId" items="${resource.labelId.split(',|，')}"
                                                   varStatus="gi">
                                            <c:if test="${s.index==gi.index}">
                                                <li><a class="font-text font-text-darkgray"
                                                       href="../labels/labels?id=${labelId.trim()}">${label.trim()}</a>
                                                </li>
                                            </c:if>
                                        </c:forEach>
                                    </c:forEach>
                                </ul>
                            </c:if>
                            <%-------------------- 资源群组 --------------------%>

                            <c:if test="${!resource.groupName.equals(\"该资源无群组\")}">
                                <ul class="resource-post-info col-md-4">
                                    <li class="font-text-darkgray">群组:&nbsp;</li>
                                    <c:forEach var="groupName" items="${resource.groupName.split(',|，')}"
                                               varStatus="gn">
                                        <c:forEach var="groupId" items="${resource.groupId.split(',|，')}"
                                                   varStatus="gi">
                                            <c:choose>
                                                <c:when test="${gi.index==gn.index}">
                                                    <li><a class="font-text-darkgray"
                                                           href="../groupinfo?groupid=${groupId.trim()}">${groupName.trim()}</a>
                                                    </li>
                                                </c:when>
                                            </c:choose>
                                        </c:forEach>
                                    </c:forEach>
                                </ul>
                            </c:if>
                            <%-------------------- 资源作者 --------------------%>
                            <ul class="resource-post-info">
                                <li class="font-text-darkgray">作者:&nbsp;</li>
                                <li><a href="/myresource?userId=${resource.userId}"
                                       class="font-text-darkgray">${user.realName}</a></li>
                            </ul>
                            <%-------------------- 资源时间 --------------------%>
                            <ul class="resource-post-info">
                                <li class="font-text-darkgray">时间:&nbsp;</li>
                                <li class="font-text-darkgray"><fmt:formatDate pattern="yyyy-MM-dd HH:mm"
                                                                               value="${resource.createTime}"/></li>
                            </ul>
                            <%-------------------- 资源操作 --------------------%>
                            <div id="operation">
                                <c:if test="${sessionScope.userId==user.id or sessionScope.roleId==1 or sessionScope.roleId==3}">
                                    <button class="re-btn re-btn-unselected re-label-child" onclick="edit()">编辑</button>
                                    <button class="re-btn re-btn-unselected re-label-child" onclick="deleteResource()">
                                        删除
                                    </button>
                                    <button id="permission" class="re-btn re-btn-unselected re-label-child"
                                            onclick="changePermission()"></button>
                                    <c:if test="${sessionScope.roleId==1 or sessionScope.roleId==3}">
                                        <button id="recommend" class="re-btn re-btn-unselected re-label-child"
                                                onclick="showRecommendOrder()"></button>
                                        <button id="notice" class="re-btn re-btn-unselected re-label-child"
                                                onclick="showNoticeOrder()"></button>
                                    </c:if>
                                </c:if>
                                <c:if test="${not empty sessionScope.userId}">
                                    <%-------------------- 导出PDF按钮 --------------------%>
                                    <button class="re-btn re-btn-unselected re-label-child"
                                            id="topdf"
                                            onclick="window.location.href='../topdf?id=${resource.id}'">导出PDF
                                    </button>

                                </c:if>
                            </div>
                        </div>
                        <%-------------------- 资源正文 --------------------%>
                        <div class="resource-post-box resource-post-article">
                            ${resource.text}
                        </div>
                        <%-------------------- 资源附件 --------------------%>
                        <c:if test="${(attachment ne '[]')&&(not empty attachment)}">
                            <div class="resource-post-box resource-post-attach">
                                <div class="font-text-darkgray">附件</div>
                                <div id="file-list"></div>
                            </div>
                        </c:if>
                    </div>
                    <%-------------------- 资源评论 --------------------%>
                    <div id="comment" class="resource-post"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- START: Footer -->
    <c:import url="../template/_footer.jsp"/>
    <!-- END: Footer -->
</div>

<div class="modal fade" id="addRecommendOrder" tabindex="-1" role="dialog" aria-labelledby="addMemberLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">设置为推荐资源</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>资源推荐排序</label>
                    <input type="text" class="form-control front-no-box-shadow" name="applicationDes"
                           id="recommendOrder" placeholder="请填写一个整数" oninput="value=value.replace(/[^\-?\d]/g,'')"/>
                </div>
            </div>
            <div class="modal-footer">
                <%--                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>--%>
                <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal"
                        onclick="recommendResource()"><span class="glyphicon glyphicon-floppy-disk"
                                                            aria-hidden="true"></span><a>确定</a></button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addNoticeOrder" tabindex="-1" role="dialog" aria-labelledby="addMemberLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">设置为公告资源</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>资源推荐排序</label>
                    <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="noticeOrder"
                           placeholder="请填写一个整数" oninput="value=value.replace(/[^\-?\d]/g,'')"/>
                </div>
            </div>
            <div class="modal-footer">
                <%--                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>--%>
                <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal"
                        onclick="noticeResource()"><span class="glyphicon glyphicon-floppy-disk"
                                                         aria-hidden="true"></span><a>确定</a></button>
            </div>
        </div>
    </div>
</div>

</body>
<!-- START: Scripts -->
<c:import url="../template/_include_js.jsp"/>

<script language="JavaScript">
    let _commentTotal = 0;
    let _thisPageTotal = 0;

    var id = ${resource.id};
    var roleId = '${sessionScope.roleId}';
    let firstGetComment = true; // 用于屏蔽首次加载评论时，屏幕滚动到评论起始

    function edit() {
        window.location.href = "<%=request.getContextPath()%>/crudres/edit?id=" + id;
    }

    $(document).ready(function () {
        getComment(1);
    })

    // 根据permissionId设置按钮文字
    $(document).ready(function () {
        // 公开操作
        if (${resource.permissionId==0}) {
            $("#permission").html("设置为公开");
        } else {
            $("#permission").html("设置为不公开");
        }
        // 推荐操作
        if (${resource.recommendType==1}) {
            $("#recommend").html("资源推荐排序为 ${resource.recommendOrder}");
            //设置资源推荐排序初始值
            document.getElementById("recommendOrder").setAttribute("value", ${resource.recommendOrder})
        } else {
            $("#recommend").html("设置为推荐");
        }
        // 公告操作
        if (${resource.noticeType==2}) {
            $("#notice").html("资源公告排序为 ${resource.noticeOrder}");
            //设置资源公告排序初始值
            document.getElementById("noticeOrder").setAttribute("value", ${resource.noticeOrder})
        } else {
            $("#notice").html("设置为公告");
        }
    })

    //设置为推荐资源按钮跳转
    function showRecommendOrder() {
        if (roleId == 1 || roleId == 3) {
            $('#addRecommendOrder').modal();
        } else {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '您没有此权限'});
        }
    }

    //设置为公告资源按钮跳转
    function showNoticeOrder() {
        if (roleId == 1 || roleId == 3) {
            $('#addNoticeOrder').modal();
        } else {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '您没有此权限'});
        }
    }

    //设置资源为推荐（ 弹窗 确定按钮调用）
    function recommendResource() {
        var recommendOrder = parseInt(document.getElementById("recommendOrder").value)
        if (isNaN(recommendOrder) || typeof recommendOrder != "number") {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '请填写一个正/负整数'});
            return false
        } else {
            loading("show");
            console.log(recommendOrder)
            $.post("../specresource/crudSpec", {
                type: 1,
                resourceId: ${resource.id},
                order: recommendOrder
            }, function (data) {
                if (data.msg == "SUCCESS") {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '资源设置推荐成功'});
                    $("#recommend").html("资源推荐排序为 " + data.order);
                    //设置资源推荐排序初始值
                    document.getElementById("recommendOrder").setAttribute("value", data.order);
                    loading("reset");
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '出问题了，重新试试！'});
                    loading("reset");
                }
            })

        }
    }

    //设置资源为公告（ 弹窗 确定按钮调用）
    function noticeResource() {
        var noticeOrder = parseInt(document.getElementById("noticeOrder").value)
        if (isNaN(noticeOrder) || typeof noticeOrder != "number") {
            $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '请填写一个正/负整数'});
            return false
        } else {
            loading("show");
            console.log(noticeOrder)
            $.post("../specresource/crudSpec", {
                type: 2,
                resourceId: ${resource.id},
                order: noticeOrder
            }, function (data) {
                if (data.msg == "SUCCESS") {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '资源设置公告成功'});
                    $("#notice").html("资源公告排序为 " + data.order);
                    //设置资源推荐排序初始值
                    document.getElementById("noticeOrder").setAttribute("value", data.order);
                    loading("reset");
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '出问题了，重新试试！'});
                    loading("reset");
                }

            })
        }
    }

    //显示附件
    var attachment = ${attachment};
    $(document).ready(function () {
        var htmlStr = $("#file-list").html();
        for (var i = 0; i < attachment.length; i++) {
            // 支持“新文件下载接口”的同时，需要兼容旧“nfs下载”！
            var url = attachment[i].url;
            if (url.indexOf("/util/downloadAttachment") != -1) {
                if (attachment[i].status == "SUCCESS") {
                    htmlStr += "<div id=\"atta" + attachment[i].id + "\" style=\"color: darkgray\" class=\"mnt-7 font-text\"><a href=\"" + attachment[i].url + "&name=" + attachment[i].name + "\">" + attachment[i].name + "</a>&nbsp&nbsp已解析</div>";
                } else if (attachment[i].status == "READY") {
                    htmlStr += "<div id=\"atta" + attachment[i].id + "\" style=\"color: darkgray\" class=\"mnt-7 font-text\"><a href=\"" + attachment[i].url + "&name=" + attachment[i].name + "\">" + attachment[i].name + "</a>&nbsp&nbsp正在解析中</div>";
                } else {
                    htmlStr += "<div id=\"atta" + attachment[i].id + "\" style=\"color: darkgray\" class=\"mnt-7 font-text\"><a href=\"" + attachment[i].url + "&name=" + attachment[i].name + "\">" + attachment[i].name + "</a>&nbsp&nbsp解析错误</div>";
                }
            } else {
                if (attachment[i].status == "SUCCESS") {
                    htmlStr += "<div id=\"atta" + attachment[i].id + "\" style=\"color: darkgray\" class=\"mnt-7 font-text\"><a href=\"" + attachment[i].url + "?flag=download&&attname=" + attachment[i].name + "\">" + attachment[i].name + "</a>&nbsp&nbsp已解析</div>";
                } else if (attachment[i].status == "READY") {

                    htmlStr += "<div id=\"atta" + attachment[i].id + "\" style=\"color: darkgray\" class=\"mnt-7 font-text\"><a href=\"" + attachment[i].url + "?flag=download&&attname=" + attachment[i].name + "\">" + attachment[i].name + "</a>&nbsp&nbsp正在解析中</div>";
                } else {
                    htmlStr += "<div id=\"atta" + attachment[i].id + "\" style=\"color: darkgray\" class=\"mnt-7 font-text\"><a href=\"" + attachment[i].url + "?flag=download&&attname=" + attachment[i].name + "\">" + attachment[i].name + "</a>&nbsp&nbsp解析错误</div>";
                }
            }
        }
        $("#file-list").html(htmlStr);
    })

    //设置资源为公开/不公开
    function changePermission() {
        $.ajax({
            url: "/resource/changePermission",
            type: "post",
            data: {
                id:${resource.id},
            },
            dataType: "text",
            success: function (data) {
                if (data == 'permissionId=0') {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '资源已设为不公开'});
                    $("#permission").html("设置为公开");
                } else {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '资源已设为公开'});
                    $("#permission").html("设置为不公开");
                }
            }
        });
    }


    //删除资源
    function deleteResource() {
        $.tipModal('confirm', 'warning', '确认删除资源吗?', function (result) {
            if (result == true) {
                for (var i = 0; i < attachment.length; i++) {
                    var attachmentId = attachment[i].id;
                    var saveUrl = attachment[i].url;
                    $.post("${pageContext.request.contextPath}/util/deleteAttachment", {
                        attachmentId: attachmentId,
                        saveUrl: saveUrl
                    });
                }
                window.location.href = "<%=request.getContextPath()%>/resource/deleteResource?id=" +${resource.id};
            }
        });
    }

    function getComment(page) {
        $("#page-data").html("");//清除页码，必要！！
        $.ajax({
            type: "get",
            url: "/resource/getComment",
            data: {
                resourceId: ${resource.id},
                page: page - 1
            },
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                $("#comment").html(data);
                let pageTotal = $('#page-total').html();
                if (pageTotal > 1) {
                    $("#page-data").html(getDivPageNumHtml(page, pageTotal, "getComment") + "<br /><br /><br /><br />");
                }
                if (firstGetComment) {
                    // 首次加载不滚动到评论起始位置
                    firstGetComment = false;
                } else {
                    // 滚动到评论起始位置，100ms
                    $('html,body').animate({
                        scrollTop: $('#comment').offset().top - 100
                    }, 100);
                }
            }
        });
    }

    function getLastComment(page) {
        $("#page-data").html("");//清除页码，必要！！
        $.ajax({
            type: "get",
            url: "/resource/getComment",
            data: {
                resourceId: ${resource.id},
                page: page - 1
            },
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                $("#comment").html(data);
                let pageTotal = $('#page-total').html();
                if (pageTotal > 1) {
                    $("#page-data").html(getDivPageNumHtml(page, pageTotal, "getComment") + "<br /><br /><br /><br />");
                }
                let count = 1;
                $("#comment-box > div").each(function () {
                    let id = $(this).attr('id');
                    if (id != 'comment-title') {
                        if (count == _thisPageTotal) {
                            // 滚动到评论起始位置，100ms
                            $('html,body').animate({
                                scrollTop: $("#" + id).offset().top - 80
                            }, 100);
                            // 展开它
                            doFold(1, id);
                        }
                        count++;
                    }
                });
            }
        });
    }

    function submitComment() {
        if (${sessionScope.login_flag==1}) {
            var content = $("#content").val();
            console.log(content.length)
            if (content.replace(/\ +/g, "").replace(/[\r\n]/g, "").trim() == "") {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '评论为空！'});
                return false;
            }
            if (content.length > 800) {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '评论超过限制字数！'});
                return false;
            }
            document.getElementById("content").value = "";
            $("#content").val("");
            var btn = $("#submitCommentButton");
            btn.attr("disabled", true);
            $.ajax({
                url: "/resource/newComment",
                type: "post",
                async: false,
                dataType: "text",
                data: {
                    content: content,
                    resourceId:${resource.id}
                },
                success: function (data) {
                    if (data == "ok") {
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '评论成功'});
                        getComment(1);
                    } else {
                        $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '评论失败'});
                    }
                },
            });
        } else {
            window.location.href = "<%=request.getContextPath()%>/login";
        }
    }

    function submitRichComment() {
        if (${sessionScope.login_flag==1}) {
            // 获取带标签的content
            var content = tinyMCE.activeEditor.getContent();
            // 获取不带标签的text
            var text = content.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g, ' ').replace(/ /g, ' ').replace(/>/g, ' ');

            // console.log('content: ' + content + ' / text: ' + text);

            if (text.replace(/\ +/g, "").replace(/[\r\n]/g, "").trim() == "") {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '评论为空！'});
                return false;
            }
            if (text.length > 800) {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '评论超过限制字数！'});
                return false;
            }
            tinyMCE.activeEditor.setContent("");
            $("#content").val("");
            var btn = $("#submitCommentButton");
            btn.attr("disabled", true);
            $.ajax({
                url: "/resource/newComment",
                type: "post",
                async: false,
                dataType: "text",
                data: {
                    content: content,
                    resourceId:${resource.id}
                },
                success: function (data) {
                    if (data == "ok") {
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '评论成功'});
                        getLastComment(parseInt(_commentTotal / 5) + 1);
                    } else {
                        $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '评论失败'});
                    }
                },
            });
        } else {
            window.location.href = "<%=request.getContextPath()%>/login";
        }
    }

    function deleteComment(commentId) {
        $.tipModal('confirm', 'warning', '确认删除评论吗?', function (result) {
            if(result==true){
                $.ajax({
                    url: "/resource/deleteComment",
                    type: "post",
                    async: false,
                    dataType: "text",
                    data: {
                        commentId: commentId,
                    },
                    success: function (data) {
                        if (data == "ok") {
                            $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '删除成功'});
                            if ((_commentTotal - 1) % 5 == 0) {
                                if (_commentTotal - 1 == 0) {
                                    getComment(1);
                                } else {
                                    getComment(parseInt((_commentTotal - 1) / 5));
                                }
                            } else {
                                getComment(parseInt((_commentTotal - 1) / 5 + 1));
                            }

                        } else {
                            $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '删除失败'});
                        }
                    },
                });
            }
        });
    }

    document.addEventListener("keydown", function (e) {
        if (e.keyCode == 13 && e.ctrlKey) {
            console.log("按下ctrl同时回车")
            $("#submitCommentButton").click();
        }
    });

    function doFold(mod, id) {
        // mod: 1.展开 / 0.收起
        if (mod == 1) {
            // 显示区域
            $('#comment-content-' + id).css('display', 'block');
            $('#comment-min-' + id).css('display', 'none');
            // 控制按钮
            $('#comment-foldOn-' + id).css('display', 'block');
            $('#comment-foldOff-' + id).css('display', 'none');
        } else {
            // 显示区域
            $('#comment-content-' + id).css('display', 'none');
            $('#comment-min-' + id).css('display', 'block');
            // 控制按钮
            $('#comment-foldOn-' + id).css('display', 'none');
            $('#comment-foldOff-' + id).css('display', 'block');
        }
    };

    /* 判断是否含有“书籍”标签 */
    $(document).ready(function () {
        let labels = '${resource.labelName}';
        if (labels.search('${bookLabelName}') != -1) {
            $('#operation').append('<button id="btn-enterBook" class="re-btn mt-2 pull-right" onclick="enterBook(${resource.id})">进入书籍</button>');
        }
    });

    /* 进入书籍 */
    function enterBook(id) {
        window.location.href = '/resource/resource?id=' + id + '&isBook=true';
    };
</script>

<!-- END: Scripts -->
</html>